package com.ykyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import com.ykyl.constant.JwtTokenManagerConstant;
import com.ykyl.constant.SecurityConstant;
import com.ykyl.constant.UserCacheConstant;
import com.ykyl.utils.JwtUtil;
import com.ykyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sjqn
 * @date 2023/11/4
 */
@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //从header中获取token
        String token = request.getHeader(SecurityConstant.USER_TOKEN);
        if (!ObjectUtil.isEmpty(token)) {
            String key = UserCacheConstant.JWT_TOKEN + token;
            String jwtJsonStr = redisTemplate.opsForValue().get(key);
            if (!ObjectUtil.isEmpty(jwtJsonStr)) {
                Claims claims = JwtUtil.parseJWT(JwtTokenManagerConstant.SECRET_KEY, jwtJsonStr);
                String currentUserStr = String.valueOf(claims.get("currentUser"));
                //存入threadLocal中
                UserThreadLocal.setSubject(currentUserStr);
            }
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
